<template>
  <a-drawer
    :title="form.watchId ? '编辑' : '添加'"
    :width="600"
    :open="visible"
    :body-style="{ paddingBottom: '80px' }"
    @close="onClose"
    destroyOnClose
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="MMSI" name="mmsi">
        <a-input v-model:value.trim="form.mmsi" placeholder="请输入MMSI" />
      </a-form-item>
      <a-form-item label="船舶名称" name="vesselName">
        <a-input v-model:value.trim="form.vesselName" placeholder="请输入船舶名称" />
      </a-form-item>
      <a-form-item label="白名单备注" name="description">
        <a-textarea v-model:value="form.description" :rows="4" placeholder="请输入白名单备注" :maxlength="255" />
      </a-form-item>
    </a-form>
    <div class="footer">
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" style="margin-right: 8px" @click="onSubmit(false)">保存</a-button>
    </div>
  </a-drawer>
</template>
<script setup>
  import { message } from 'ant-design-vue';
  import _ from 'lodash';
  import { reactive, ref } from 'vue';
  import { SmartLoading } from '/src/components/framework/smart-loading';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { shipType } from '/@/config/shipType';
  //
  import { api } from '/src/api/plat/watch.js';
  // emit
  const emit = defineEmits(['refresh']);

  // ----------------------- 显示/隐藏 ---------------------

  const visible = ref(false); // 是否展示抽屉
  // 隐藏
  function onClose() {
    reset();
    visible.value = false;
  }
  // 显示
  async function showDrawer(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    visible.value = true;
  }

  const formRef = ref(); // 组件ref
  const formDefault = {
    watchId: undefined,
    watchType: 2,
    vesselType: undefined,
    vesselName: undefined,
    mmsi: undefined,
    description: undefined,
  };

  let form = reactive(_.cloneDeep(formDefault));
  function reset() {
    Object.assign(form, formDefault);
    formRef.value.resetFields();
  }

  // ----------------------- 表单提交 ---------------------
  // 表单规则
  const validateMMSI = async (_rule, value) => {
    const regex = /^\d{9}$/;
    if (!regex.test(value)) {
      return Promise.reject('请输入正确的9位MMSI');
    } else {
      return Promise.resolve();
    }
  };
  const rules = {
    vesselType: [{ required: true, message: '船舶类型不能为空' }],
    vesselName: [{ required: true, message: '船舶名称不能为空' }],
    mmsi: [
      { required: true, message: 'MMSI不能为空' },
      { validator: validateMMSI, trigger: 'change' },
    ],
  };

  // 校验表单
  function validateForm(formRef) {
    return new Promise((resolve) => {
      formRef
        .validate()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    });
  }

  // 提交数据
  async function onSubmit(keepAdding) {
    let validateFormRes = await validateForm(formRef.value);
    if (!validateFormRes) {
      message.error('参数验证错误，请仔细填写表单数据!');
      return;
    }
    SmartLoading.show();
    submitForm(keepAdding);
  }

  async function submitForm(keepAdding) {
    try {
      if (form.watchId) {
        await api.update(form);
      } else {
        await api.add(form);
      }
      message.success('提交成功');
      if (keepAdding) {
        reset();
      } else {
        onClose();
      }
      emit('refresh');
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    showDrawer,
  });
</script>
<style scoped lang="less">
  .footer {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e9e9e9;
    padding: 10px 16px;
    background: #fff;
    text-align: right;
    z-index: 1;
  }
  .hint {
    margin-top: 5px;
    color: #bfbfbf;
  }
</style>
